package com.serial.comm.core.interceptor;

import com.serial.comm.core.constants.properties.FODBProperties;
import com.serial.comm.core.reqres.response.ResponseData;
import com.serial.comm.core.utils.CollectionKit;
import com.serial.comm.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @version: V1.0
 * @author: chentailai
 * @description: 拦截指定请求，检查是否包含 apiKey
 * @className: IdentityFilter
 * @packageName: IdentityFilter.java
 * @data: 2020/5/28 14:04
 **/
@Slf4j
@Component
public class IdentityInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private FODBProperties fodbProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info(">>>>>>进入前置拦截器");
        //不包含在配置中的url请求地址默认放过
        String spath = request.getServletPath();
        if (!CollectionKit.contains(fodbProperties.getVerifyUrls(), spath)) {
            return true;
        }

        //校验请求头
        String successKey = fodbProperties.getApiKey();
        String key_header = request.getHeader("apiKey");
        if (StringUtils.isNotBlank(key_header)) {
            if (!key_header.equals(successKey)) {
                log.info(">>>>>>请求头中apiKey不合法,禁止访问");
                returnInvalid(response, new ResponseData(false, 401, "请求头中apiKey不合法", null));
                return false;
            }
        } else {
            String key_param = request.getParameter("apiKey");
            if (StringUtils.isNotBlank(key_param)) {
                if (!key_param.equals(successKey)) {
                    log.info(">>>>>>请求头中apiKey不合法,禁止访问");
                    returnInvalid(response, new ResponseData(false, 401, "请求头中apiKey不合法", null));
                    return false;
                }
            } else {
                log.info(">>>>>>请求头中apiKey为空,禁止访问");
                returnInvalid(response, new ResponseData(false, 401, "请求头中apiKey为空", null));
                return false;
            }

        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    /**
     * @Author chentailai
     * @Description 返回错误理由
     * @Param [response, data]
     * @Return void
     * @Date 2020/5/28 14:11
     */
    private void returnInvalid(HttpServletResponse response, ResponseData data) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(data);
        } catch (IOException e) {
            log.error("拦截器返回时出现异常");
        } finally {
            if (writer != null)
                writer.close();
        }
    }
}
